package yunquan.wang.base.spring.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import yunquan.wang.base.dao.MatchType;
import yunquan.wang.base.dao.QueryHelper;
import yunquan.wang.base.dao.springdata.RepositoryUtils;
import yunquan.wang.modules.base.entity.RulesInfo;
import yunquan.wang.modules.base.entity.UserBasic;

public class SpringSecurityUtils {
	/**
	 * 取得当前用户, 返回值为SpringSecurity的User类或其子类, 如果当前用户未登录则返回null.
	 */
	@SuppressWarnings("unchecked")
	public static <T extends User> T getCurrentUser() {
		Authentication authentication = getAuthentication();
		if (authentication != null) {
			Object principal = authentication.getPrincipal();
			if (principal instanceof User) {
				return (T) principal;
			}
		}
		return null;
	}
/**
 * 获取当前的权限规则
 * @return
 */
	public static Set<RulesInfo> getCurrentRules() {
		Authentication authentication = getAuthentication();
		Set<RulesInfo> rulesInfo=new HashSet<RulesInfo>();
		if (authentication == null) {
			return null;
		} else {
			for(GrantedAuthority authority:authentication.getAuthorities())
			{
				if(authority instanceof GrantedAuthorityRulesImpl)
				{
					GrantedAuthorityRulesImpl granred=(GrantedAuthorityRulesImpl)	authority;
					if(granred.getIsCurentUse())
					{
						rulesInfo.addAll(granred.getRulesInfo());
					}
				}
			}
		}
		return rulesInfo;
	}

	
	/**
     * Security Rules
     */
	public static  Specification addSecurityRules(Specification specification)
	{
		 Set<RulesInfo> allRules=getCurrentRules() ;
		 
		 for(RulesInfo ruleinfo:allRules)
		 {
			 String type = ruleinfo.getType();
				if(type.equalsIgnoreCase(RulesInfo.RULE_TYPE_PROERTY))
				 {
					specification=	QueryHelper.addSpecification(specification, ruleinfo.getName(), MatchType.EQ,ruleinfo.getValue()); 
				 }
				else if(type.equalsIgnoreCase(RulesInfo.RULE_TYPE_SQL))
				{
					//TODO
				}
				else
				{
		 
				 UserDetail user=SpringSecurityUtils.getCurrentUser ();
					if(type.equalsIgnoreCase(RulesInfo.RULE_TYPE_USER))
					 {
						specification=	QueryHelper.addSpecification(specification,"createUser.id", MatchType.EQ, user.getUserId()); 
					 }
					else if(type.equalsIgnoreCase(RulesInfo.RULE_TYPE_GROUP))
					{
//						specification=	QueryHelper.addSpecification(specification,"createUser.goupInfo.id", MatchType.EQ, user.getUserId()); 
//						specifications=specifications.and(RepositoryUtils.exist("createUser.goupInfo.id", user.getGroupId(), UserBasic.class));
					}
		 
			 else
			 {
		//exception
			 }
				}
		 }
		return specification;
		//USER_EQ_user
		//USER_IN_GROUP
		
		//
		//type user, user id in 
	}
 
 
	/**
	 * 取得当前用户的登录名, 如果当前用户未登录则返回空字符串.
	 */
	public static String getCurrentUserName() {
		Authentication authentication = getAuthentication();
		if (authentication != null && authentication.getPrincipal() != null) {
			return authentication.getName();
		}
		return "";
	}

	/**
	 * 取得当前用户登录IP, 如果当前用户未登录则返回空字符串.
	 */
	public static String getCurrentUserIp() {
		Authentication authentication = getAuthentication();
		if (authentication != null) {
			Object details = authentication.getDetails();
			if (details instanceof WebAuthenticationDetails) {
				WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;
				return webDetails.getRemoteAddress();
			}
		}

		return "";
	}

	/**
	 * 判断用户是否拥有角色, 如果用户拥有参数中的任意一个角色则返回true.
	 */
	public static boolean hasAnyRole(String[] roles) {
		Authentication authentication = SecurityContextHolder.getContext()
				.getAuthentication();
		Collection<GrantedAuthority> granteds = (Collection<GrantedAuthority>) authentication
				.getAuthorities();
		for (String role : roles) {
			for (GrantedAuthority authority : granteds) {
				if (role.equals(authority.getAuthority())) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 将UserDetails保存到Security Context.
	 * 
	 * @param userDetails
	 *            已初始化好的用户信息.
	 * @param request
	 *            用于获取用户IP地址信息.
	 */
	public static void saveUserDetailsToContext(UserDetails userDetails,
			HttpServletRequest request) {
		PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(
				userDetails, userDetails.getPassword(),
				userDetails.getAuthorities());

		authentication.setDetails(new WebAuthenticationDetails(request));

		SecurityContextHolder.getContext().setAuthentication(authentication);
	}

	/**
	 * 取得Authentication, 如当前SecurityContext为空时返回null.
	 */
	public static Authentication getAuthentication() {
		SecurityContext context = SecurityContextHolder.getContext();
		if (context != null) {
			return context.getAuthentication();
		}
		return null;
	}

}
